import Transaction from '../api/transaction/transaction';

export default class ParseCSVToTeam {
    static parse = async (event): Promise<Array<Transaction>> => {
        const promise: Promise<Array<Transaction>> = new Promise(function (resolve) {
            if (event.target.files && event.target.files[0]) {
                const file = event.target.files[0];

                // if (file.size > 1024) { console.log("File size cannot exceed more than 1MB"); }

                const reader = new FileReader();

                reader.addEventListener('load', function (event) {
                    const data = event.target.result;
                    const team = ParseCSVToTeam.convertToList(data.toString());
                    resolve(team);
                });

                reader.readAsBinaryString(file);
            }
        });

        return await promise;
    };

    static convertToList = (data: string): Array<Transaction> => {
        const transactions = new Array<Transaction>();

        const split = data.split('\n');

        for (let i = 1; i < split.length; i++) {
            if (split[i]) {
                let details = split[i].split(',');

                details = details.map((detail) => detail.replace('\r', '').trim());
                const isRowValid = details.some((detail) => detail !== '');

                if (!isRowValid) {
                    continue;
                }

                const transaction = new Transaction();
                transaction.csvLine = i;
                transaction.name = details[0];
                transaction.amount = /^\d*\.?\d+$/.test(details[1]) ? parseFloat(details[1]) : -1;
                transaction.walletAddress = details[2].replaceAll(' ', '');
                transaction.email = details[3];

                transactions.push(transaction);
            }
        }

        return transactions;
    };
}
